#ifndef _BitUtil_h_
#define _BitUtil_h_

#include "system.h"

static inline uint32_t GetBitsMask(int high, int low) {
	return high == 31 ? 0xffffffff - (1 << (low)) + 1 : (1 << (high + 1)) - (1 << (low));
}

static inline uint32_t SetBits(uint32_t *value, int high, int low, uint32_t bitsValue) {
	uint32_t mask = GetBitsMask(high, low);
	*value = (*value & ~mask) | ((bitsValue << low) & mask);
	return *value;
}

static inline void SetBit(uint32_t *value, int bit) {
	uint32_t mask = 1 << bit;
	*value |= mask;
}

static inline uint32_t MergeBit(int bit, Bool bitValue) {
	return bitValue << bit;
}

static inline Bool GetBit(unsigned int value, int bit) {
	return (value >> bit) & 1;
}

static inline void ClrBit(uint32_t *value, int bit) {
	uint32_t mask = 1 << bit;
	*value &= ~mask;
}

static inline uint32_t SetBitByMask(uint32_t *value, uint32_t mask, Bool bitValue) {
	uint32_t tmp = *value;
	if (bitValue)
		tmp |= mask;
	else
		tmp &= ~mask;
	*value = tmp;
	return *value;
}

static inline uint32_t SetBitValue(uint32_t *value, int bit, Bool bitValue) {
	return SetBitByMask(value, 1 << bit, bitValue);
}

static inline uint32_t GetBits(uint32_t value, int high, int low) {
	uint32_t mask = GetBitsMask(high, low);
	return (value & mask) >> low;
}

static inline uint8_t GetByte(uint32_t value, int i) {
	return ((uint8_t *)&value)[i];
}

#endif
